package boot.spring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import boot.spring.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson.JSONObject;
import boot.spring.entity.UserInfo;
import boot.spring.service.UserInfoService;
import boot.spring.util.JwtUtils;

//token拦截器 实现HandlerInterceptor接口
@Component
public class TokenInterceptor implements HandlerInterceptor {

	@Autowired
	private UserInfoService userInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 从请求头中获取token
		System.out.println(request.getHeader("test"+" :tt"));
		String token = request.getHeader("token");
		String t = request.getParameter("token");
		System.out.println(t);
		System.out.println("token"+token);
		System.out.println("是否到了这里————————————————————————");
		//判断token是否为空
		if(t != null && t != "") {
			//获取token中的用户名
			String userName = JwtUtils.getUserName(t);
			//根据用户名查询用户信息
			Users user = userInfoService.getUserByName(userName);
			//验证token是否有效
			boolean checkSign = JwtUtils.checkSign(t);
			if(user!=null && checkSign) {
				System.out.println("是否到了这里—————————————222———————————");
				return true;
			}
		}
		//返回输出格式
        JSONObject json = new JSONObject();
        json.put("success", "false");
        json.put("msg", "token异常");
        json.put("code", "0");
		json.put("a", "a");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().append(json.toString());
        
		return false;
	}
}
